package com.gec.teams.wechat.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.gec.teams.wechat.mapper.TbDeptMapper;
import com.gec.teams.wechat.mapper.TbUserMapper;
import com.gec.teams.wechat.pojo.Dto.UserLoginDto;
import com.gec.teams.wechat.pojo.TbDept;
import com.gec.teams.wechat.pojo.User;
import com.gec.teams.wechat.pojo.entity.MessageEntity;
import com.gec.teams.wechat.pojo.vo.TbUserVo;
import com.gec.teams.wechat.pojo.vo.UserDeptVo;
import com.gec.teams.wechat.service.UserService;
import com.gec.teams.wechat.exception.TeamsException;
import com.gec.teams.wechat.task.MessageTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 功能：
 * 作者：YumTea
 * 日期：2024/6/11 14:39
 */
@Service
//代表这个是多例的bean
@Scope("prototype")
@Slf4j
public class UserServiceImpl implements UserService {

    @Value("${wx.app-id}")
    private String appId;
    @Value("${wx.app-secret}")
    private String appSecret;
    @Autowired
    private TbUserMapper tbUserMapper;
    @Autowired
    private TbDeptMapper tbDeptMapper;
    @Autowired
    private MessageTask messageTask;

    private String getOpenId(String code) {
            String url="https://api.weixin.qq.com/sns/jscode2session";
        HashMap map = new HashMap();
        map.put("appid", appId);
        map.put("secret", appSecret);
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String response = HttpUtil.post(url, map);
        JSONObject jsonObject = JSONUtil.parseObj(response);
        String openid = jsonObject.getStr("openid");
        if(openid==null||openid.equals("")){
            throw new TeamsException("获取openid失败");
        }
        return openid;
    }



    public int registerUser(String registerCode, String code, String nickname, String photo){
//        先判断你的openID能不能拿到先
        String openId = getOpenId(code);
        if(tbUserMapper.haveOpenId(openId)) throw new TeamsException("账号已经存在，请登录",201);
        TbUserVo user = TbUserVo.builder()
                .root(false)
                .nickname(nickname)
                .createTime(new Date())
                .openId(openId)
                .hiredate(new Date())
                .status(1)
                .photo(photo)
                .deptName("未分配")
                .name(nickname)
                .build();
        //如果是注册超级管理员
        if(registerCode.equals("000000")){
//            如果存在超级管理员，那就爪巴
            if(tbUserMapper.haveRootUser()) throw new TeamsException("已经存在超级管理员");
            user.setRole("[0]");
//            获取openId
            //TODO 根据注册码来决定部门 还有权限
            user.setRoot(true);
            tbUserMapper.insertInt(user);
            MessageEntity entity = new MessageEntity();
            entity.setSenderId(0);//系统发送设为0
            entity.setSenderName("系统消息");
            entity.setUuid(IdUtil.simpleUUID());
            entity.setMsg("欢迎您注册成为超级管理员,请及时更新你的员工个人信息");
            entity.setSendTime(new Date());
            messageTask.sendAsync(user.getId().toString(),entity);
            return user.getId();
        }
//        如果不是注册超级管理员的
        user.setRole("[1, 2, 3, 4, 5, 6, 7, 8]");
        int i = tbUserMapper.insertInt(user);

//        发送消息
        MessageEntity entity = new MessageEntity();
        entity.setSenderId(0);//系统发送设为0
        entity.setSenderName("系统消息");
        entity.setUuid(IdUtil.simpleUUID());
        entity.setMsg("欢迎您注册成为超级管理员,请及时更新你的员工个人信息");
        entity.setSendTime(new Date());
        messageTask.sendAsync(user.getId().toString(),entity);
        return i;
    }

    @Override
    public UserDeptVo login(String code) {
        String openId = getOpenId(code);
        UserLoginDto user = tbUserMapper.getIdByOpenId(openId);
        if(ObjectUtil.isEmpty(user.getId())) throw new TeamsException("该用户未注册,请先注册");
        if(ObjectUtil.isEmpty(user.getStatus())) throw new TeamsException("该用户已被冻结，请联系管理员");
        UserDeptVo userDeptVo=tbUserMapper.getUserAndDept(user.getId());
       messageTask.receiveAsync(userDeptVo.getId().toString());
        return userDeptVo;
    }

    @Override
    public Set<String> getsearchUserPermissions(int id) {
        return tbUserMapper.getsearchUserPermissions(id);
    }

    @Override
    public String searchUserHiredate(int userId) {
        return tbUserMapper.searchUserHiredate(userId);
    }

    @Override
    public ArrayList<HashMap> searchUserGroupByDept(String keyword) {
        ArrayList<HashMap> list_1=tbDeptMapper.searchDeptMembers(keyword);
        ArrayList<HashMap> list_2=tbUserMapper.searchUserGroupByDept(keyword);
        //为部门添加员工
        for(HashMap map_1:list_1){
            long deptId=(Long)map_1.get("id");
            ArrayList members=new ArrayList();
            for(HashMap map_2:list_2){
                long id=(Long) map_2.get("deptId");
                if(deptId==id){
                    members.add(map_2);
                }
            }
            map_1.put("members",members);
        }
        return list_1;
    }

    @Override
    public ArrayList<HashMap> searchMembers(List param){
        return tbUserMapper.searchMembers(param);
    }

}
